p2pnode = None

def start(args):
    
    from .client import P2PClient
    from .netnode import P2PNetNode
    from .server import P2PServer
    
    loader = args['loader']
    rpc = loader.get_component('rpc')
    router = loader.get_component('server.WSGI_Server').get_router()
    
    p2pnode = P2PNetNode()
    
    loader.register_component('p2p.P2PNetNode', P2PNetNode)
    loader.register_component('p2p.P2PClient', P2PClient)
    loader.register_component('p2p.P2PServer', P2PServer)
    
    # TODO: parameterize the port
    p2pnode.start(4242)

    #@rpc.function('p2p.connect')
    #def connect(address: str):
    @rpc.function('p2p.connect')
    def connect(address):
        p2pnode.connect(address)
    
    #@rpc.function('p2p.disconnect')
    #def disconnect(address: str):
    @rpc.function('p2p.disconnect')
    def disconnect(address):
        p2pnode.close(address)
    
    #@rpc.function('p2p.is_connected')
    #def is_connected(address: str):
    @rpc.function('p2p.is_connected')
    def is_connected(address):
        return p2pnode.is_connected(address)
    
    #@rpc.function('p2p.send')
    #def send(address: str, data: str):
    @rpc.function('p2p.send')
    def send(address, data):
        p2pnode.send(address, data)
    
def stop(args):
    json = loader.get_component('rpc')
    for function in ('p2p.connect', 'p2p.disconnect', 'p2p.is_connected', 'p2p.send'):
        json.rpc.remove_function(function)
    p2pnode.stop()
    p2pnode = None
